package com.xqboss.apps.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xqboss.apps.constant.Config;
import com.xqboss.apps.domain.hama.HamaHelp;
import com.xqboss.apps.enums.hama.HamaConfigNumberPeopleEnum;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.user.WalletLidouChangeTypeEnum;
import com.xqboss.apps.service.hama.HamaHelpService;
import com.xqboss.apps.service.hama.HamaUserMixService;
import com.xqboss.apps.util.mh.MoneyUtils;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.utils.DateUtils;
import com.xqboss.system.service.ISysConfigService;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 运动场队员助力空投力豆
 *
 * @author ljh
 * @date 2024/3/1
 */

@Slf4j
@Component
public class SportTeamListener extends MqListener {

    @Autowired
    private HamaHelpService hamaHelpService;
    @Autowired
    private HamaUserMixService hamaUserMixService;
    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public MqEnum getEnum() {
        return AppMqDelayEnum.SPORT_TEAM;
    }

    @Override
    public ConsumeResult solve(MessageView message) {
        String value = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        List<Long> userIds= JSONArray.parseArray(value, Long.class);
        Date date = Date.from(LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).atZone(ZoneId.systemDefault()).toInstant());//当前整点小时
        airdropTeam(userIds,date);
        return ConsumeResult.SUCCESS;
    }
    public void airdropTeam(List<Long> userIds,Date indexTime) {
        log.info("--------time:{},hama-init-user-help:{}",indexTime, userIds);
        if(CollectionUtils.isNotEmpty(userIds)){
            BigDecimal factor = this.sysConfigService.getValue(Config.Sys.Sport.间推助力系数);
            List<HamaHelp> helps = new ArrayList<>();//修改一级，修改字段（开始生产时间、累计助力金额）
            List<HamaHelp> helpsNext = new ArrayList<>();//修改二级，修改字段（二级累计助力金额）
            List<HelpIncome> helpIncomes = new ArrayList<>();//助力收益
            HamaHelp help ;//一级
            HamaHelp helpN ;//二级
            for (int i=0;i<userIds.size();i++){
                Long parentUserId=userIds.get(i);
                BigDecimal helpNewTotal = BigDecimal.ZERO;//新人助力总和 - 一级
                BigDecimal helpOldTotal = BigDecimal.ZERO;//老人助力总和 - 一级
                BigDecimal helpNewTotalNext = BigDecimal.ZERO;//新人助力总和 - 二级
                BigDecimal helpOldTotalNext = BigDecimal.ZERO;//老人助力总和 - 二级
                List<HamaHelp> helpList=hamaHelpService.list(Wrappers.<HamaHelp>lambdaQuery().eq(HamaHelp::getParentUserId,parentUserId).eq(HamaHelp::getIsRealName,Boolean.TRUE));
                for(HamaHelp hamaHelp:helpList){
                    if (hamaHelp.getBasicSpeed().compareTo(BigDecimal.ZERO) > 0) {
                        help = new HamaHelp();
                        //新人助力
                        if(hamaHelp.getIsPeople()== HamaConfigNumberPeopleEnum.NEW){
                            int hireTime = (int) DateUtils.subtractMin(hamaHelp.getHireTime(), indexTime);
                            if(hireTime>0){
                                int time = (int) DateUtils.subtractMin(indexTime,hamaHelp.getStartProductionTime());
                                if(time>0){
                                    //计算当前用户上级的收益
                                    BigDecimal helpNum = MoneyUtils.multipleToScale6(hamaHelp.getBasicSpeed(), DateUtils.minToHour(time));
                                    helpNewTotal = helpNewTotal.add(helpNum);//累计
                                    help.setEggLayingNum(MoneyUtils.add(helpNum,hamaHelp.getEggLayingNum()));
                                }
                            }else {
                                //雇佣时间到期
                                int time = (int) DateUtils.subtractMin(hamaHelp.getHireTime(),hamaHelp.getStartProductionTime());
                                if(time>0){
                                    //计算当前用户上级的收益
                                    BigDecimal helpNum = MoneyUtils.multipleToScale6(hamaHelp.getBasicSpeed(), DateUtils.minToHour(time));
                                    helpNewTotal = helpNewTotal.add(helpNum);//累计
                                    help.setEggLayingNum(MoneyUtils.add(helpNum,hamaHelp.getEggLayingNum()));
                                    help.setBasicSpeed(BigDecimal.ZERO);
                                }
                            }
                        }else if(hamaHelp.getIsPeople()==HamaConfigNumberPeopleEnum.OLD){
                            //老人助力
                            int time = (int) DateUtils.subtractMin(indexTime,hamaHelp.getStartProductionTime());
                            if(time>0){
                                //计算当前用户助力天灵珠多少
                                BigDecimal helpNum = MoneyUtils.multipleToScale6(hamaHelp.getBasicSpeed(), DateUtils.minToHour(time));
                                helpOldTotal = helpOldTotal.add(helpNum);//累计
                                help.setEggLayingNum(MoneyUtils.add(hamaHelp.getEggLayingNum(),helpNum));
                            }
                        }
                        help.setStartProductionTime(indexTime);
                        help.setId(hamaHelp.getId());
                        helps.add(help);
                    }

                    // 二级新人/老人助力，这里的二级：是我的队员创建的队伍邀请的人
                    List<HamaHelp> childHelpList =hamaHelpService.list(Wrappers.<HamaHelp>lambdaQuery().eq(HamaHelp::getParentUserId,hamaHelp.getChildUserId()).eq(HamaHelp::getIsRealName,Boolean.TRUE).gt(HamaHelp::getBasicSpeed,BigDecimal.ZERO));
                    if (CollUtil.isNotEmpty(childHelpList)) {
                        for (HamaHelp helpNext : childHelpList) {
                            helpN = new HamaHelp();
                            helpN.setId(helpNext.getId());
                            helpN.setEggLayingNumIndirect(BigDecimal.ZERO);
                            //二级新人助力
                            if(helpNext.getIsPeople()== HamaConfigNumberPeopleEnum.NEW){
                                int hireTime = (int) DateUtils.subtractMin(helpNext.getHireTime(), indexTime);
                                if(hireTime>0){
                                    int time = (int) DateUtils.subtractMin(indexTime,helpNext.getStartProductionTime());
                                    if(time>0){
                                        //计算当前用户上级的收益
                                        BigDecimal helpNum = MoneyUtils.multipleToScale6(helpNext.getBasicSpeed(), DateUtils.minToHour(time));
                                        helpNum =MoneyUtils.multipleToScale6(helpNum,factor);//间推助力系数后助力
                                        helpNewTotalNext = helpNewTotalNext.add(helpNum);//累计
                                        helpN.setEggLayingNumIndirect(MoneyUtils.add(helpNum,helpNext.getEggLayingNumIndirect()));
                                    }
                                }else {
                                    //雇佣时间到期
                                    int time = (int) DateUtils.subtractMin(helpNext.getHireTime(),helpNext.getStartProductionTime());
                                    if(time>0){
                                        //计算当前用户上级的收益
                                        BigDecimal helpNum = MoneyUtils.multipleToScale6(helpNext.getBasicSpeed(), DateUtils.minToHour(time));
                                        helpNum =MoneyUtils.multipleToScale6(helpNum,factor);//间推助力系数后助力
                                        helpNewTotalNext = helpNewTotalNext.add(helpNum);//累计
                                        helpN.setEggLayingNumIndirect(MoneyUtils.add(helpNum,helpNext.getEggLayingNumIndirect()));
                                    }
                                }
                            }else if(helpNext.getIsPeople()==HamaConfigNumberPeopleEnum.OLD){
                                //二级老人助力
                                int time = (int) DateUtils.subtractMin(indexTime,helpNext.getStartProductionTime());
                                if(time>0){
                                    //计算当前用户助力天灵珠多少
                                    BigDecimal helpNum = MoneyUtils.multipleToScale6(helpNext.getBasicSpeed(), DateUtils.minToHour(time));
                                    helpNum =MoneyUtils.multipleToScale6(helpNum,factor);//间推助力系数后助力
                                    helpOldTotalNext = helpOldTotalNext.add(helpNum);//累计
                                    helpN.setEggLayingNumIndirect(MoneyUtils.add(hamaHelp.getEggLayingNumIndirect(),helpNum));
                                }
                            }
                            if(helpN.getEggLayingNumIndirect().compareTo(BigDecimal.ZERO)>0)helpsNext.add(helpN);
                        }
                    }
                }
                helpIncomes.add(HelpIncome.builder().parentUserId(parentUserId).helpNewTotal(helpNewTotal).helpOldTotal(helpOldTotal).helpNewTotalNext(helpNewTotalNext).helpOldTotalNext(helpOldTotalNext).build());
            }
            // 【step：1】修改字段（开始生产时间、累计助力金额）
            if(CollUtil.isNotEmpty(helps))hamaHelpService.updateBatchById(helps,helps.size());
            // 【step：2】修改字段（二级累计助力金额）
            if(CollUtil.isNotEmpty(helpsNext))hamaHelpService.updateBatchById(helpsNext,helpsNext.size());
            // 【step：3】助力收益（给队长空投力豆助力收益）
            if (CollUtil.isNotEmpty(helpIncomes)) {
                for (HelpIncome in : helpIncomes) {
                    Long parentUserId = in.getParentUserId();//队长id
                    BigDecimal helpNewTotal = in.getHelpNewTotal();//新人助力总和 - 一级
                    BigDecimal helpOldTotal = in.getHelpOldTotal();//老人助力总和 - 一级
                    BigDecimal helpNewTotalNext = in.getHelpNewTotalNext();//新人助力总和 - 二级
                    BigDecimal helpOldTotalNext = in.getHelpOldTotalNext();//老人助力总和 - 二级
                    // 新人
                    if(helpNewTotal.compareTo(BigDecimal.ZERO) > 0){
                        //给上级增加助力收益
                        hamaUserMixService.addIncome(parentUserId, 0L,helpNewTotal, WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_NEW);
                    }
                    // 老人
                    if(helpOldTotal.compareTo(BigDecimal.ZERO) > 0){
                        //给上级增加助力收益
                        hamaUserMixService.addIncome(parentUserId, 0L,helpOldTotal, WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_OLD);
                    }
                    // 新人-二级
                    if(helpNewTotalNext.compareTo(BigDecimal.ZERO) > 0){
                        //给上级增加助力收益
                        hamaUserMixService.addIncome(parentUserId, 1L,helpNewTotalNext, WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_NEW_NEXT);
                    }
                    // 老人-二级
                    if(helpOldTotalNext.compareTo(BigDecimal.ZERO) > 0){
                        //给上级增加助力收益
                        hamaUserMixService.addIncome(parentUserId, 1L,helpOldTotalNext, WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_OLD_NEXT);
                    }
                }
            }
        }
    }
}

/**
 * 助力收益
 */
@Data
@Builder
class HelpIncome{
    Long parentUserId;//队长id
    BigDecimal helpNewTotal;//新人助力总和 - 一级
    BigDecimal helpOldTotal;//老人助力总和 - 一级
    BigDecimal helpNewTotalNext;//新人助力总和 - 二级
    BigDecimal helpOldTotalNext;//老人助力总和 - 二级
}